﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Betfairer
{
    public class TableDao
    {
        private const char COLON_SPLITTER = ':';
        private const char TILDE_SPLITTER = '~';
        private const char PIPE_SPLITTER = '|';

        public Table GetTable(Int32 marketId)
        {
            List<Cell[]> table = new List<Cell[]>();
            String marketString = Global.Instance.GetMarketPricesCompressed(marketId);

            string[] records = marketString.Split(COLON_SPLITTER);

            decimal inPairSum = 0;

            for (int i = 1; i < records.Length; ++i)
            {
                decimal inPair;

                table.Add(ParseRider(records[i], out inPair));
                inPairSum += inPair;
            }

            return new Table(table, inPairSum);
        }

        private Cell[] ParseRider(String rider, out Decimal inPair)
        {
            String[] subriders = rider.Split(PIPE_SPLITTER);

            String header = subriders[0];
            String back = subriders[1];
            String lay = subriders[2];

            IEnumerable<Cell> result = ParseHalfRider(back).Reverse().Concat(ParseHalfRider(lay));

            inPair = ParseHeader(header);

            return result.ToArray();
        }

        private decimal ParseHeader(String header)
        {
            String[] tokens = header.Split(TILDE_SPLITTER);

            return Convert.ToDecimal(tokens[2], System.Globalization.CultureInfo.InvariantCulture);
        }

        private Cell[] ParseHalfRider(String halfRider)
        {
            List<Cell> result = new List<Cell>();
            String[] tokens = halfRider.Split(TILDE_SPLITTER);

            for (int i = 0; i < tokens.Length - 1; i += 4)
            {
                result.Add(new Cell(Convert.ToDecimal(tokens[i]
                    , System.Globalization.CultureInfo.InvariantCulture),
                    Convert.ToDecimal(tokens[i + 1]
                    , System.Globalization.CultureInfo.InvariantCulture)));
            }

            return result.ToArray();
        }
    }
}
